//index.js
import mqtt from '../../utils/mqtt.min.js'; //根据自己存放的路径修改
import { hex_hmac_sha1 } from '../../utils/hex_hmac_sha1.js'; //根据自己存放的路径修改
const app = getApp()

Page({
	data: {
		productKey : "a13RXPFSBnM",
		deviceName : "FrYSFbWJi9EYHhvEa9Ln",
		deviceSecret: "xurB5FPisXGXJ2veWUvjEDZN8K9so1SJ",
		regionId: "cn-shanghai",
		status_server: "未连接",
		status_topic: "未订阅",
		indicatorDots: true,
		vertical: false,
		autoplay: true,
		interval: 5000,
		duration: 500,
		arrayImage: ["../../image/ali.jpg", 
			"../../image/tencent.jpg", 
			"../../image/onenet.jpg",
			"../../image/rtt.jpg",
		],
		//所有图片的高度  
		imgheights: [],
		//图片宽度 
		imgwidth: 750,
		//默认  
		current: 0
	},
	onLoad: function () {
	},
	onShow: function () {
    	console.log("Onshow......");
	},
	
	btn_connect: function() {
		this.ConnectAliyunServer();
	},

	ConnectAliyunServer(){
		var that = this
		const deviceConfig = {
			productKey  : that.data.productKey,
			deviceName  : that.data.deviceName,
			deviceSecret: that.data.deviceSecret,
			regionId    : that.data.regionId
		};
		const options = that.initMqttOptions(deviceConfig);
		// 替换productKey为你自己的产品的
		const mqttClient = mqtt.connect('wxs://a13RXPFSBnM.iot-as-mqtt.cn-shanghai.aliyuncs.com',options);
		mqttClient.on('connect', function () {
			console.log('连接服务器成功')
			that.setData({
				status_server:"已连接"
			})
			//订阅主题，替换productKey和deviceName(这里的主题可能会不一样，具体请查看后台设备Topic列表或使用自定义主题)
			var topic = '/a13RXPFSBnM/FrYSFbWJi9EYHhvEa9Ln/user/get';
			mqttClient.subscribe(topic, function (err) {
				if (!err) {
						console.log('订阅成功！');
						that.setData({
						status_topic:"已订阅"
					})
				}
			})
			mqttClient.on('message', function (topic, message){
				console.log("接收信息：" + message.toString());
			})
		})
	},
  	//IoT平台mqtt连接参数初始化
	initMqttOptions(deviceConfig) {
		const params = {
			productKey: deviceConfig.productKey,
			deviceName: deviceConfig.deviceName,
			timestamp: Date.now(),
			clientId: Math.random().toString(36).substr(2),
		}
		//CONNECT参数
		const options = {
			keepalive: 60,     //60s
			clean: true,       //cleanSession不保持持久会话
			protocolVersion: 4 //MQTT v3.1.1
		}
		//1.生成clientId，username，password
		options.password = this.signHmacSha1(params, deviceConfig.deviceSecret);
		options.clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
		options.username = `${params.deviceName}&${params.productKey}`;
		return options;
  },
	signHmacSha1(params, deviceSecret) {
		let keys = Object.keys(params).sort();
		// 按字典序排序
		keys = keys.sort();
		const list = [];
		keys.map((key) => {
			list.push(`${key}${params[key]}`);
		});
		const contentStr = list.join('');
		return hex_hmac_sha1(deviceSecret, contentStr); 
	}
})
